<template>
	<view class="component-page">
		<view class="page-header">
			<view class="back-button" @click="backToHome">
				<text class="back-icon">←</text>
				<text>返回</text>
			</view>
			<text class="page-title">多端支付聚合SDK</text>
		</view>
		
		<view class="demo-section">
			<view class="section-title">
				支付流程演示
			</view>
			
			<view class="payment-demo">
				<view class="payment-product">
					<image class="product-image" src="/static/images/product-demo.png" mode="aspectFit"></image>
					<view class="product-info">
						<text class="product-title">高级会员套餐</text>
						<text class="product-desc">包含一年高级会员权益</text>
						<text class="product-price">¥299.00</text>
					</view>
				</view>
				
				<view class="payment-options">
					<view class="payment-title">选择支付方式</view>
					
					<view class="payment-method" 
						v-for="(method, index) in paymentMethods" 
						:key="method.id"
						:class="{'selected': selectedMethod === index}"
						@click="selectPaymentMethod(index)"
					>
						<view class="method-icon">{{ method.icon }}</view>
						<view class="method-info">
							<text class="method-name">{{ method.name }}</text>
							<text class="method-desc">{{ method.desc }}</text>
						</view>
						<view class="method-check">
							<text class="check-icon" v-if="selectedMethod === index">✓</text>
						</view>
					</view>
					
					<view class="payment-virtual" v-if="canUseVirtual">
						<view class="virtual-header">
							<view class="virtual-title">使用积分抵扣</view>
							<view class="virtual-balance">可用积分: {{ userPoints }}</view>
						</view>
						<view class="virtual-input">
							<input 
								type="number" 
								v-model="usePoints" 
								placeholder="请输入要使用的积分"
								class="points-input"
							/>
							<text class="points-rate">100积分 = 1元</text>
						</view>
						<text class="discount-amount" v-if="discountAmount > 0">
							已抵扣 ¥{{ discountAmount.toFixed(2) }}
						</text>
					</view>
					
					<view class="payment-summary">
						<view class="summary-row">
							<text>商品金额</text>
							<text>¥299.00</text>
						</view>
						<view class="summary-row" v-if="discountAmount > 0">
							<text>积分抵扣</text>
							<text>-¥{{ discountAmount.toFixed(2) }}</text>
						</view>
						<view class="summary-row total">
							<text>实付金额</text>
							<text>¥{{ (299 - discountAmount).toFixed(2) }}</text>
						</view>
					</view>
					
					<button class="payment-button" @click="handlePayment">立即支付</button>
				</view>
			</view>
		</view>
		
		<view class="demo-section">
			<view class="section-title">订单记录</view>
			<view class="orders-list" v-if="orders.length > 0">
				<view 
					v-for="order in orders" 
					:key="order.id"
					class="order-item"
				>
					<view class="order-header">
						<text class="order-id">订单号: {{ order.id.substring(0, 8) }}...</text>
						<text class="order-status" :class="`status-${order.status.toLowerCase()}`">
							{{ getStatusText(order.status) }}
						</text>
					</view>
					<view class="order-content">
						<text class="order-title">{{ order.title }}</text>
						<text class="order-amount">¥{{ order.amount.toFixed(2) }}</text>
					</view>
					<view class="order-footer">
						<text class="order-time">{{ formatOrderTime(order.createdAt) }}</text>
						<view class="order-actions">
							<button 
								class="action-btn query-btn" 
								@click="queryOrderStatus(order.id)"
								v-if="['CREATED', 'PAYING'].includes(order.status)"
							>
								查询
							</button>
							<button 
								class="action-btn close-btn" 
								@click="closeOrder(order.id)"
								v-if="['CREATED', 'PAYING'].includes(order.status)"
							>
								关闭
							</button>
							<button 
								class="action-btn refund-btn" 
								@click="refundOrder(order.id)"
								v-if="['PAID', 'SUCCESS'].includes(order.status)"
							>
								退款
							</button>
						</view>
					</view>
				</view>
			</view>
			<view class="empty-orders" v-else>
				<text>暂无订单记录</text>
			</view>
		</view>
		
		<view class="payment-result" v-if="showResult">
			<view class="result-content">
				<view class="result-icon" :class="{'success': paymentResult.success, 'failed': !paymentResult.success}">
					<text v-if="paymentResult.success">✓</text>
					<text v-else>✗</text>
				</view>
				<text class="result-title">{{ paymentResult.title }}</text>
				<text class="result-message">{{ paymentResult.message }}</text>
				<button class="result-button" @click="closeResult">确定</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import xlPayment from '@/components/xl-payment';

// 当前选择的支付方式
const selectedMethod = ref(0);
// 用户可用积分
const userPoints = ref(3000);
// 使用的积分
const usePoints = ref('');
// 订单列表
const orders = ref([]);
// 是否显示支付结果
const showResult = ref(false);
// 支付结果信息
const paymentResult = ref({
  success: false,
  title: '',
  message: ''
});

// 支付方式列表
const paymentMethods = ref([
  { id: 'wechat', name: '微信支付', desc: '推荐使用微信支付', icon: '📱' },
  { id: 'alipay', name: '支付宝', desc: '支付宝安全支付', icon: '💳' },
  { id: 'unionpay', name: '银联支付', desc: '银联在线支付', icon: '🏦' }
]);

// 是否能使用虚拟货币支付
const canUseVirtual = computed(() => {
  return selectedMethod.value !== -1 && userPoints.value > 0;
});

// 积分抵扣金额
const discountAmount = computed(() => {
  if (!usePoints.value) return 0;
  const points = parseInt(usePoints.value);
  if (isNaN(points) || points <= 0) return 0;
  
  // 不能超过用户可用积分
  const validPoints = Math.min(points, userPoints.value);
  
  // 100积分 = 1元
  return validPoints / 100;
});

// 返回首页
const backToHome = () => {
  uni.navigateBack();
};

// 选择支付方式
const selectPaymentMethod = (index) => {
  selectedMethod.value = index;
};

// 处理支付
const handlePayment = async () => {
  const paymentType = paymentMethods.value[selectedMethod.value].id;
  const pointsToUse = parseInt(usePoints.value) || 0;
  
  // 创建订单
  const createOrderResult = await xlPayment.createOrder({
    title: '高级会员套餐',
    amount: 299,
    paymentType: paymentType,
    virtualAmount: pointsToUse / 100, // 积分转换为元
    metadata: {
      userId: '12345',
      productId: 'vip_annual'
    }
  });
  
  if (!createOrderResult.success) {
    showPaymentResult(false, '创建订单失败', createOrderResult.error?.message || '请稍后重试');
    return;
  }
  
  // 添加到订单列表
  orders.value.unshift(createOrderResult.order);
  
  // 发起支付
  const payResult = await xlPayment.pay({
    orderId: createOrderResult.order.id
  });
  
  if (payResult.success) {
    if (payResult.pending) {
      // H5跳转支付等异步场景
      showPaymentResult(true, '已跳转支付', '请在新页面完成支付');
    } else {
      // 支付成功
      showPaymentResult(true, '支付成功', `支付金额: ¥${(299 - discountAmount.value).toFixed(2)}`);
      
      // 更新用户积分
      if (pointsToUse > 0) {
        userPoints.value -= pointsToUse;
        usePoints.value = '';
      }
    }
  } else {
    if (payResult.canceled) {
      showPaymentResult(false, '支付取消', '您已取消支付');
    } else {
      showPaymentResult(false, '支付失败', payResult.message || '请稍后重试');
    }
  }
};

// 查询订单状态
const queryOrderStatus = async (orderId) => {
  const result = await xlPayment.queryOrder(orderId);
  
  if (result.success) {
    // 更新订单状态
    const index = orders.value.findIndex(o => o.id === orderId);
    if (index !== -1) {
      orders.value[index] = result.order;
    }
    
    // 显示查询结果
    showPaymentResult(true, '查询成功', `订单状态: ${getStatusText(result.order.status)}`);
  } else {
    showPaymentResult(false, '查询失败', result.message || '请稍后重试');
  }
};

// 关闭订单
const closeOrder = async (orderId) => {
  const result = await xlPayment.closeOrder(orderId);
  
  if (result.success) {
    // 更新订单状态
    const index = orders.value.findIndex(o => o.id === orderId);
    if (index !== -1) {
      orders.value[index] = result.order;
    }
    
    showPaymentResult(true, '关闭成功', '订单已关闭');
  } else {
    showPaymentResult(false, '关闭失败', result.message || '请稍后重试');
  }
};

// 退款订单
const refundOrder = async (orderId) => {
  const result = await xlPayment.refund({
    orderId: orderId,
    reason: '用户申请退款'
  });
  
  if (result.success) {
    // 更新订单状态
    const index = orders.value.findIndex(o => o.id === orderId);
    if (index !== -1) {
      orders.value[index] = result.order;
    }
    
    showPaymentResult(true, '退款成功', '退款申请已提交');
  } else {
    showPaymentResult(false, '退款失败', result.message || '请稍后重试');
  }
};

// 显示支付结果
const showPaymentResult = (success, title, message) => {
  paymentResult.value = {
    success,
    title,
    message
  };
  showResult.value = true;
};

// 关闭结果弹窗
const closeResult = () => {
  showResult.value = false;
};

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    'CREATED': '待支付',
    'PAYING': '支付中',
    'PAID': '已支付',
    'SUCCESS': '支付成功',
    'FAILED': '支付失败',
    'CLOSED': '已关闭',
    'REFUNDED': '已退款',
    'PARTIAL_REFUNDED': '部分退款'
  };
  return statusMap[status] || status;
};

// 格式化订单时间
const formatOrderTime = (timeStr) => {
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 初始化
onMounted(async () => {
  // 初始化支付SDK
  await xlPayment.initialize({
    config: {
      // 虚拟货币配置
      virtual: {
        enabled: true,
        name: '积分',
        rate: 100,  // 100积分=1元
        checkBalance: async () => {
          // 模拟从服务端获取用户积分余额
          return { success: true, balance: userPoints.value };
        }
      }
    }
  });
  
  // 监听支付状态变化
  xlPayment.store.addEventListener('orderStatusChange', (order) => {
    // 更新订单列表中的状态
    const index = orders.value.findIndex(o => o.id === order.id);
    if (index !== -1) {
      orders.value[index] = order;
    }
    
    // 如果是成功支付，显示成功结果
    if (order.status === 'PAID' || order.status === 'SUCCESS') {
      showResult.value = true;
      paymentResult.value = {
        success: true,
        title: '支付成功',
        message: `订单支付成功！金额: ¥${order.amount.toFixed(2)}`
      };
    }
  });
  
  // 加载本地订单
  loadLocalOrders();
});

// 从本地加载订单记录
const loadLocalOrders = () => {
  try {
    const orderData = uni.getStorageSync('xl_payment_orders');
    if (orderData) {
      orders.value = JSON.parse(orderData);
    }
  } catch (e) {
    console.error('加载订单记录失败:', e);
  }
};
</script>

<style lang="scss">
.component-page {
	padding: 30rpx;
	background-color: #f7f7f7;
	min-height: 100vh;
	box-sizing: border-box;
}

.page-header {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
	
	.back-button {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		margin-right: 20rpx;
		
		.back-icon {
			font-size: 36rpx;
			margin-right: 6rpx;
		}
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
}

.demo-section {
	margin-bottom: 30rpx;
	
	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
}

/* 支付SDK样式 */
.payment-demo {
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	margin-bottom: 30rpx;
	
	.payment-product {
		display: flex;
		padding: 30rpx;
		border-bottom: 1px solid #f5f5f5;
		background: linear-gradient(135deg, #f9f9f9 0%, #f2f2f2 100%);
		
		.product-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 12rpx;
			margin-right: 24rpx;
			background-color: #fff;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		}
		
		.product-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			
			.product-title {
				font-size: 34rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 8rpx;
			}
			
			.product-desc {
				font-size: 26rpx;
				color: #666;
				margin-bottom: 20rpx;
			}
			
			.product-price {
				font-size: 40rpx;
				font-weight: bold;
				color: #ff6600;
			}
		}
	}
	
	.payment-options {
		padding: 30rpx;
		
		.payment-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 24rpx;
			position: relative;
			padding-left: 20rpx;
			
			&:before {
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 6rpx;
				height: 30rpx;
				background-color: #007aff;
				border-radius: 6rpx;
			}
		}
		
		.payment-method {
			display: flex;
			align-items: center;
			padding: 24rpx;
			margin-bottom: 16rpx;
			background-color: #f9f9f9;
			border-radius: 12rpx;
			transition: all 0.3s ease;
			
			&:active {
				background-color: #f0f0f0;
			}
			
			&.selected {
				background-color: rgba(0, 122, 255, 0.05);
				border: 1px solid rgba(0, 122, 255, 0.3);
			}
			
			.method-icon {
				width: 60rpx;
				height: 60rpx;
				font-size: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #fff;
				border-radius: 50%;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
				margin-right: 20rpx;
			}
			
			.method-info {
				flex: 1;
				
				.method-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 4rpx;
				}
				
				.method-desc {
					font-size: 24rpx;
					color: #999;
				}
			}
			
			.method-check {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				border: 1px solid #ddd;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;
				
				.check-icon {
					color: #fff;
					font-size: 24rpx;
				}
				
				&:has(.check-icon) {
					background-color: #007aff;
					border-color: #007aff;
				}
			}
		}
		
		.payment-virtual {
			margin-top: 30rpx;
			background-color: #f9f9f9;
			border-radius: 12rpx;
			padding: 24rpx;
			
			.virtual-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				
				.virtual-title {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
				}
				
				.virtual-balance {
					font-size: 24rpx;
					color: #ff6600;
					background-color: rgba(255, 102, 0, 0.1);
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
				}
			}
			
			.virtual-input {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				
				.points-input {
					flex: 1;
					height: 70rpx;
					background-color: #fff;
					border: 1px solid #eee;
					border-radius: 8rpx;
					padding: 0 20rpx;
					font-size: 28rpx;
					margin-right: 20rpx;
				}
				
				.points-rate {
					font-size: 24rpx;
					color: #999;
				}
			}
			
			.discount-amount {
				display: block;
				text-align: right;
				font-size: 26rpx;
				color: #ff6600;
				font-weight: bold;
			}
		}
		
		.payment-summary {
			margin-top: 30rpx;
			background-color: #f9f9f9;
			border-radius: 12rpx;
			padding: 24rpx;
			
			.summary-row {
				display: flex;
				justify-content: space-between;
				margin-bottom: 16rpx;
				font-size: 26rpx;
				color: #666;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				&.total {
					margin-top: 16rpx;
					padding-top: 16rpx;
					border-top: 1px dashed #ddd;
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					
					text:last-child {
						color: #ff6600;
					}
				}
			}
		}
		
		.payment-button {
			margin-top: 40rpx;
			height: 88rpx;
			line-height: 88rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #fff;
			background: linear-gradient(90deg, #007aff 0%, #0055ff 100%);
			border-radius: 44rpx;
			box-shadow: 0 6rpx 15rpx rgba(0, 122, 255, 0.3);
			transition: all 0.3s ease;
			
			&:active {
				transform: translateY(3rpx);
				box-shadow: 0 3rpx 8rpx rgba(0, 122, 255, 0.3);
			}
		}
	}
}

.orders-list {
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	
	.order-item {
		padding: 24rpx;
		border-bottom: 1px solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;
			
			.order-id {
				font-size: 24rpx;
				color: #999;
			}
			
			.order-status {
				padding: 4rpx 12rpx;
				border-radius: 20rpx;
				font-size: 22rpx;
				
				&.status-created {
					background-color: rgba(128, 128, 128, 0.1);
					color: #666;
				}
				
				&.status-paying {
					background-color: rgba(255, 149, 0, 0.1);
					color: #ff9500;
				}
				
				&.status-paid, &.status-success {
					background-color: rgba(76, 217, 100, 0.1);
					color: #4cd964;
				}
				
				&.status-closed {
					background-color: rgba(255, 59, 48, 0.1);
					color: #ff3b30;
				}
				
				&.status-refunded {
					background-color: rgba(142, 142, 147, 0.1);
					color: #8e8e93;
				}
			}
		}
		
		.order-content {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;
			
			.order-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}
			
			.order-amount {
				font-size: 32rpx;
				color: #ff6600;
				font-weight: bold;
			}
		}
		
		.order-footer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.order-time {
				font-size: 24rpx;
				color: #999;
			}
			
			.order-actions {
				display: flex;
				
				.action-btn {
					margin-left: 16rpx;
					padding: 6rpx 20rpx;
					font-size: 24rpx;
					border-radius: 20rpx;
					
					&.query-btn {
						background-color: rgba(0, 122, 255, 0.1);
						color: #007aff;
					}
					
					&.close-btn {
						background-color: rgba(142, 142, 147, 0.1);
						color: #8e8e93;
					}
					
					&.refund-btn {
						background-color: rgba(255, 59, 48, 0.1);
						color: #ff3b30;
					}
				}
			}
		}
	}
}

.empty-orders {
	padding: 60rpx 0;
	text-align: center;
	background-color: #fff;
	border-radius: 16rpx;
	color: #999;
	font-size: 28rpx;
}

.payment-result {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
	
	.result-content {
		width: 600rpx;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		padding: 40rpx;
		text-align: center;
		
		.result-icon {
			width: 120rpx;
			height: 120rpx;
			margin: 0 auto 30rpx;
			border-radius: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 60rpx;
			
			&.success {
				background-color: rgba(76, 217, 100, 0.1);
				color: #4cd964;
			}
			
			&.failed {
				background-color: rgba(255, 59, 48, 0.1);
				color: #ff3b30;
			}
		}
		
		.result-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}
		
		.result-message {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 40rpx;
		}
		
		.result-button {
			height: 88rpx;
			line-height: 88rpx;
			font-size: 32rpx;
			color: #fff;
			background-color: #007aff;
			border-radius: 44rpx;
		}
	}
}
</style> 